package com.example.emos.api.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.emos.api.common.util.PageUtils;
import com.example.emos.api.common.util.R;
import com.example.emos.api.controller.form.ApprovalTaskForm;
import com.example.emos.api.controller.form.ArchiveTaskForm;
import com.example.emos.api.controller.form.SearchApprovalContentForm;
import com.example.emos.api.controller.form.SearchTaskByPageForm;
import com.example.emos.api.exception.EmosException;
import com.example.emos.api.service.ApprovalService;
import com.example.emos.api.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/approval")
@Tag(name = "ApprovalController", description = "任务审批Web接口")
@Slf4j
public class ApprovalController {
    @Value("${workflow.url}")
    private String workflow;

    @Value("${emos.code}")
    private String code;

    @Value("${emos.tcode}")
    private String tcode;

    @Autowired
    private UserService userService;

    @Autowired
    private ApprovalService approvalService;

    @PostMapping("/searchTaskByPage")
    @Operation(summary = "查询分页任务列表")
    @SaCheckPermission(value = {"WORKFLOW:APPROVAL", "FILE:ARCHIVE"}, mode = SaMode.OR)
    public R searchTaskByPage(@Valid @RequestBody SearchTaskByPageForm form) {
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        int userId = StpUtil.getLoginIdAsInt();
        param.put("userId", userId);
        param.put("role", userService.searchUserRoles(userId));
//        PageUtils pageUtils = approvalService.searchTaskByPage(param);
        List<JSONObject> list = Arrays.asList(new JSONObject().set("createName", "花哥").set("title", "测试线上会议申请").set("type", "会议申请")
                .set("filling", false).set("processId", IdUtil.randomUUID()).set("taskId", IdUtil.randomUUID()).set("createDate", "2021-10-10").set("status", "待审批"));
        Long totalCount = 1L;
        Integer pageIndex = 1;
        Integer pageSize = 1;
        PageUtils pageUtils = new PageUtils(list, totalCount, pageIndex, pageSize);
        return R.ok().put("page", pageUtils);
    }

    @PostMapping("/searchApprovalContent")
    @Operation(summary = "查询任务详情")
    @SaCheckPermission(value = {"WORKFLOW:APPROVAL", "FILE:ARCHIVE"}, mode = SaMode.OR)
    public R searchApprovalContent(@Valid @RequestBody SearchApprovalContentForm form) {
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        int userId = StpUtil.getLoginIdAsInt();
        param.put("userId", userId);
        param.put("role", userService.searchUserRoles(userId));
//        HashMap content = approvalService.searchApprovalContent(param);
        HashMap content = new HashMap<>();
        content.put("date", "2021-10-10");
        content.put("result", "success");
        content.put("hours", 2);
        content.put("members", "花哥、花落知多少");
        content.put("start", "8:30");
        content.put("end", "9:30");
        content.put("name", "花哥");
        content.put("id", 1);
        content.put("type", 1);
        content.put("uuid", IdUtil.simpleUUID());
        content.put("desc", "这是一个测试用的线上会议申请");
        content.put("place", "线上会议");
        content.put("photod", "https://cdn.jsdelivr.net/gh/31346337/image-hosting@master/images/3.4bhw3jroxro0.jpg、https://static-1258386385.cos.ap-beijing.myqcloud.com/img/header/0709201917506.jpg");
        return R.ok().put("content", content);
    }

    @GetMapping("/searchApprovalBpmn")
    @Operation(summary = "获取BPMN图形")
    @SaCheckPermission(value = {"WORKFLOW:APPROVAL", "FILE:ARCHIVE"}, mode = SaMode.OR)
    public void searchApprovalBpmn(String instanceId, HttpServletResponse response) throws IOException {
//        if (StrUtil.isBlankIfStr(instanceId)) {
//            throw new EmosException("instanceId不能为空");
//        }
//        HashMap param = new HashMap() {{
//            put("code", code);
//            put("tcode", tcode);
//            put("instanceId", instanceId);
//        }};
//        String url = workflow + "/workflow/searchApprovalBpmn";
//        HttpResponse resp = HttpRequest.post(url).header("content-type", "application/json")
//                .body(JSONUtil.toJsonStr(param)).execute();
//        if (resp.getStatus() == 200) {
//            try (
//                    InputStream in = resp.bodyStream();
//                    BufferedInputStream bin = new BufferedInputStream(in);
//                    OutputStream out = response.getOutputStream();
//                    BufferedOutputStream bout = new BufferedOutputStream(out);
//            ) {
//                IoUtil.copy(bin, bout);
//            } catch (Exception e) {
//                log.error("执行异常", e);
//            }
//        } else {
//            log.error("获取工作流BPMN失败");
//            throw new EmosException("获取工作流BPMN失败");
//        }
        String base64 = "";
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = decoder.decodeBuffer(base64);
        try (
                ByteArrayInputStream in = IoUtil.toStream(bytes);
                BufferedInputStream bin = new BufferedInputStream(in);
                OutputStream out = response.getOutputStream();
                BufferedOutputStream bout = new BufferedOutputStream(out);
        ) {
            IoUtil.copy(bin, bout);
        } catch (IORuntimeException e) {
            e.printStackTrace();
        }

    }

    @PostMapping("/approvalTask")
    @Operation(summary = "审批任务")
    @SaCheckPermission(value = {"WORKFLOW:APPROVAL"}, mode = SaMode.OR)
    public R approvalTask(@Valid @RequestBody ApprovalTaskForm form) {
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
//        approvalService.approvalTask(param);
        return R.ok();
    }

    @PostMapping("/archiveTask")
    @Operation(summary = "归档任务")
    @SaCheckPermission(value = {"FILE:ARCHIVE"})
    public R archiveTask(ArchiveTaskForm form) {
        return R.ok();
    }


}
